<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"chentianming11.github.io","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":"default"},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":{"enable":true,"onlypost":false,"loadingImg":"/uploads/loading.gif"},"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="之前也写过一篇关于Spring Validation使用的文章，不过自我感觉还是浮于表面，本次打算彻底搞懂Spring Validation。本文会详细介绍Spring Validation各种场景下的最佳实践及其实现原理，死磕到底！项目源码：spring-validation">
<meta property="og:type" content="article">
<meta property="og:title" content="Spring Validation最佳实践及其实现原理，参数校验没那么简单！">
<meta property="og:url" content="https://chentianming11.github.io/posts/3181057117/index.html">
<meta property="og:site_name" content="伍六七">
<meta property="og:description" content="之前也写过一篇关于Spring Validation使用的文章，不过自我感觉还是浮于表面，本次打算彻底搞懂Spring Validation。本文会详细介绍Spring Validation各种场景下的最佳实践及其实现原理，死磕到底！项目源码：spring-validation">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-08-01T06:37:50.000Z">
<meta property="article:modified_time" content="2020-08-05T00:44:24.405Z">
<meta property="article:author" content="陈添明">
<meta property="article:tag" content="spring">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://chentianming11.github.io/posts/3181057117/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>Spring Validation最佳实践及其实现原理，参数校验没那么简单！ | 伍六七</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">伍六七</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">一起学Java</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签<span class="badge">6</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类<span class="badge">3</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档<span class="badge">17</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

  <a href="https://github.com/chentianming11" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://chentianming11.github.io/posts/3181057117/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="陈添明">
      <meta itemprop="description" content="一个爱看国漫的程序猿">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="伍六七">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Spring Validation最佳实践及其实现原理，参数校验没那么简单！
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-08-01 14:37:50" itemprop="dateCreated datePublished" datetime="2020-08-01T14:37:50+08:00">2020-08-01</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-08-05 08:44:24" itemprop="dateModified" datetime="2020-08-05T08:44:24+08:00">2020-08-05</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/spring/" itemprop="url" rel="index"><span itemprop="name">spring</span></a>
                </span>
            </span>

          
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="far fa-comment"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/posts/3181057117/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/posts/3181057117/" itemprop="commentCount"></span>
    </a>
  </span>
  
  <br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="far fa-file-word"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>14k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="far fa-clock"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>34 分钟</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>之前也写过一篇关于<code>Spring Validation</code>使用的文章，不过自我感觉还是浮于表面，本次打算彻底搞懂<code>Spring Validation</code>。本文会详细介绍<code>Spring Validation</code>各种场景下的最佳实践及其实现原理，死磕到底！<br>项目源码：<a href="https://github.com/chentianming11/spring-validation" target="_blank" rel="noopener">spring-validation</a></p>
<a id="more"></a>

<h2 id="简单使用"><a href="#简单使用" class="headerlink" title="简单使用"></a>简单使用</h2><p><code>Java API</code>规范(<code>JSR303</code>)定义了<code>Bean</code>校验的标准<code>validation-api</code>，但没有提供实现。<code>hibernate validation</code>是对这个规范的实现，并增加了校验注解如<code>@Email</code>、<code>@Length</code>等。<code>Spring Validation</code>是对<code>hibernate validation</code>的二次封装，用于支持<code>spring mvc</code>参数自动校验。接下来，我们以<code>spring-boot</code>项目为例，介绍<code>Spring Validation</code>的使用。</p>
<h3 id="引入依赖"><a href="#引入依赖" class="headerlink" title="引入依赖"></a>引入依赖</h3><p>如果<code>spring-boot</code>版本小于<code>2.3.x</code>，<code>spring-boot-starter-web</code>会自动传入<code>hibernate-validator</code>依赖。如果<code>spring-boot</code>版本大于<code>2.3.x</code>，则需要手动引入依赖：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.hibernate<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>hibernate-validator<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>6.0.1.Final<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>对于<code>web</code>服务来说，为防止非法参数对业务造成影响，在<code>Controller</code>层一定要做参数校验的！大部分情况下，请求参数分为如下两种形式：</p>
<ol>
<li><code>POST</code>、<code>PUT</code>请求，使用<code>requestBody</code>传递参数；</li>
<li><code>GET</code>请求，使用<code>requestParam/PathVariable</code>传递参数。</li>
</ol>
<p>下面我们简单介绍下<code>requestBody</code>和<code>requestParam/PathVariable</code>的参数校验实战！</p>
<h3 id="requestBody参数校验"><a href="#requestBody参数校验" class="headerlink" title="requestBody参数校验"></a><code>requestBody</code>参数校验</h3><p><code>POST</code>、<code>PUT</code>请求一般会使用<code>requestBody</code>传递参数，这种情况下，后端使用<strong>DTO对象</strong>进行接收。<strong>只要给DTO对象加上<code>@Validated</code>注解就能实现自动参数校验</strong>。比如，有一个保存<code>User</code>的接口，要求<code>userName</code>长度是<code>2-10</code>，<code>account</code>和<code>password</code>字段长度是<code>6-20</code>。如果校验失败，会抛出<code>MethodArgumentNotValidException</code>异常，<code>Spring</code>默认会将其转为<code>400（Bad Request）</code>请求。</p>
<blockquote>
<p><strong>DTO表示数据传输对象（Data Transfer Object），用于服务器和客户端之间交互传输使用的</strong>。在spring-web项目中可以表示用于接收请求参数的<code>Bean</code>对象。</p>
</blockquote>
<ul>
<li><strong>在<code>DTO</code>字段上声明约束注解</strong></li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UserDTO</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> Long userId;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@NotNull</span></span><br><span class="line">    <span class="meta">@Length</span>(min = <span class="number">2</span>, max = <span class="number">10</span>)</span><br><span class="line">    <span class="keyword">private</span> String userName;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@NotNull</span></span><br><span class="line">    <span class="meta">@Length</span>(min = <span class="number">6</span>, max = <span class="number">20</span>)</span><br><span class="line">    <span class="keyword">private</span> String account;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@NotNull</span></span><br><span class="line">    <span class="meta">@Length</span>(min = <span class="number">6</span>, max = <span class="number">20</span>)</span><br><span class="line">    <span class="keyword">private</span> String password;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li><strong>在方法参数上声明校验注解</strong></li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@PostMapping</span>(<span class="string">"/save"</span>)</span><br><span class="line"><span class="function"><span class="keyword">public</span> Result <span class="title">saveUser</span><span class="params">(@RequestBody @Validated UserDTO userDTO)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 校验通过，才会执行业务逻辑处理</span></span><br><span class="line">    <span class="keyword">return</span> Result.ok();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>这种情况下，<strong>使用<code>@Valid</code>和<code>@Validated</code>都可以</strong>。</p>
</blockquote>
<h3 id="requestParam-PathVariable参数校验"><a href="#requestParam-PathVariable参数校验" class="headerlink" title="requestParam/PathVariable参数校验"></a><code>requestParam/PathVariable</code>参数校验</h3><p><code>GET</code>请求一般会使用<code>requestParam/PathVariable</code>传参。如果参数比较多(比如超过6个)，还是推荐使用<code>DTO</code>对象接收。否则，推荐将一个个参数平铺到方法入参中。在这种情况下，<strong>必须在<code>Controller</code>类上标注<code>@Validated</code>注解，并在入参上声明约束注解(如<code>@Min</code>等)</strong>。如果校验失败，会抛出<code>ConstraintViolationException</code>异常。代码示例如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RequestMapping</span>(<span class="string">"/api/user"</span>)</span><br><span class="line"><span class="meta">@RestController</span></span><br><span class="line"><span class="meta">@Validated</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UserController</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 路径变量</span></span><br><span class="line">    <span class="meta">@GetMapping</span>(<span class="string">"&#123;userId&#125;"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> Result <span class="title">detail</span><span class="params">(@PathVariable(<span class="string">"userId"</span>)</span> @<span class="title">Min</span><span class="params">(<span class="number">10000000000000000</span>L)</span> Long userId) </span>&#123;</span><br><span class="line">        <span class="comment">// 校验通过，才会执行业务逻辑处理</span></span><br><span class="line">        UserDTO userDTO = <span class="keyword">new</span> UserDTO();</span><br><span class="line">        userDTO.setUserId(userId);</span><br><span class="line">        userDTO.setAccount(<span class="string">"11111111111111111"</span>);</span><br><span class="line">        userDTO.setUserName(<span class="string">"xixi"</span>);</span><br><span class="line">        userDTO.setAccount(<span class="string">"11111111111111111"</span>);</span><br><span class="line">        <span class="keyword">return</span> Result.ok(userDTO);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 查询参数</span></span><br><span class="line">    <span class="meta">@GetMapping</span>(<span class="string">"getByAccount"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> Result <span class="title">getByAccount</span><span class="params">(@Length(min = <span class="number">6</span>, max = <span class="number">20</span>)</span> @NotNull String  account) </span>&#123;</span><br><span class="line">        <span class="comment">// 校验通过，才会执行业务逻辑处理</span></span><br><span class="line">        UserDTO userDTO = <span class="keyword">new</span> UserDTO();</span><br><span class="line">        userDTO.setUserId(<span class="number">10000000000000003L</span>);</span><br><span class="line">        userDTO.setAccount(account);</span><br><span class="line">        userDTO.setUserName(<span class="string">"xixi"</span>);</span><br><span class="line">        userDTO.setAccount(<span class="string">"11111111111111111"</span>);</span><br><span class="line">        <span class="keyword">return</span> Result.ok(userDTO);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="统一异常处理"><a href="#统一异常处理" class="headerlink" title="统一异常处理"></a>统一异常处理</h3><p>前面说过，如果校验失败，会抛出<code>MethodArgumentNotValidException</code>或者<code>ConstraintViolationException</code>异常。在实际项目开发中，通常会用<strong>统一异常处理</strong>来返回一个更友好的提示。比如我们系统要求无论发送什么异常，<code>http</code>的状态码必须返回<code>200</code>，由业务码去区分系统的异常情况。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RestControllerAdvice</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CommonExceptionHandler</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@ExceptionHandler</span>(&#123;MethodArgumentNotValidException<span class="class">.<span class="keyword">class</span>&#125;)</span></span><br><span class="line"><span class="class">    @<span class="title">ResponseStatus</span>(<span class="title">HttpStatus</span>.<span class="title">OK</span>)</span></span><br><span class="line"><span class="class">    @<span class="title">ResponseBody</span></span></span><br><span class="line"><span class="class">    <span class="title">public</span> <span class="title">Result</span> <span class="title">handleMethodArgumentNotValidException</span>(<span class="title">MethodArgumentNotValidException</span> <span class="title">ex</span>) </span>&#123;</span><br><span class="line">        BindingResult bindingResult = ex.getBindingResult();</span><br><span class="line">        StringBuilder sb = <span class="keyword">new</span> StringBuilder(<span class="string">"校验失败:"</span>);</span><br><span class="line">        <span class="keyword">for</span> (FieldError fieldError : bindingResult.getFieldErrors()) &#123;</span><br><span class="line">            sb.append(fieldError.getField()).append(<span class="string">"："</span>).append(fieldError.getDefaultMessage()).append(<span class="string">", "</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        String msg = sb.toString();</span><br><span class="line">       <span class="keyword">return</span> Result.fail(BusinessCode.参数校验失败, msg);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@ExceptionHandler</span>(&#123;ConstraintViolationException<span class="class">.<span class="keyword">class</span>&#125;)</span></span><br><span class="line"><span class="class">    @<span class="title">ResponseStatus</span>(<span class="title">HttpStatus</span>.<span class="title">OK</span>)</span></span><br><span class="line"><span class="class">    @<span class="title">ResponseBody</span></span></span><br><span class="line"><span class="class">    <span class="title">public</span> <span class="title">Result</span> <span class="title">handleConstraintViolationException</span>(<span class="title">ConstraintViolationException</span> <span class="title">ex</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> Result.fail(BusinessCode.参数校验失败, ex.getMessage());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="进阶使用"><a href="#进阶使用" class="headerlink" title="进阶使用"></a>进阶使用</h2><h3 id="分组校验"><a href="#分组校验" class="headerlink" title="分组校验"></a>分组校验</h3><p>在实际项目中，可能多个方法需要使用同一个<code>DTO</code>类来接收参数，而不同方法的校验规则很可能是不一样的。这个时候，简单地在<code>DTO</code>类的字段上加约束注解无法解决这个问题。因此，<code>spring-validation</code>支持了<strong>分组校验</strong>的功能，专门用来解决这类问题。还是上面的例子，比如保存<code>User</code>的时候，<code>UserId</code>是可空的，但是更新<code>User</code>的时候，<code>UserId</code>的值必须<code>&gt;=10000000000000000L</code>；其它字段的校验规则在两种情况下一样。这个时候使用<strong>分组校验</strong>的代码示例如下：</p>
<ul>
<li><strong>约束注解上声明适用的分组信息<code>groups</code></strong></li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UserDTO</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Min</span>(value = <span class="number">10000000000000000L</span>, groups = Update<span class="class">.<span class="keyword">class</span>)</span></span><br><span class="line"><span class="class">    <span class="title">private</span> <span class="title">Long</span> <span class="title">userId</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@NotNull</span>(groups = &#123;Save<span class="class">.<span class="keyword">class</span>, <span class="title">Update</span>.<span class="title">class</span>&#125;)</span></span><br><span class="line"><span class="class">    @<span class="title">Length</span>(<span class="title">min</span> </span>= <span class="number">2</span>, max = <span class="number">10</span>, groups = &#123;Save<span class="class">.<span class="keyword">class</span>, <span class="title">Update</span>.<span class="title">class</span>&#125;)</span></span><br><span class="line"><span class="class">    <span class="title">private</span> <span class="title">String</span> <span class="title">userName</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@NotNull</span>(groups = &#123;Save<span class="class">.<span class="keyword">class</span>, <span class="title">Update</span>.<span class="title">class</span>&#125;)</span></span><br><span class="line"><span class="class">    @<span class="title">Length</span>(<span class="title">min</span> </span>= <span class="number">6</span>, max = <span class="number">20</span>, groups = &#123;Save<span class="class">.<span class="keyword">class</span>, <span class="title">Update</span>.<span class="title">class</span>&#125;)</span></span><br><span class="line"><span class="class">    <span class="title">private</span> <span class="title">String</span> <span class="title">account</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@NotNull</span>(groups = &#123;Save<span class="class">.<span class="keyword">class</span>, <span class="title">Update</span>.<span class="title">class</span>&#125;)</span></span><br><span class="line"><span class="class">    @<span class="title">Length</span>(<span class="title">min</span> </span>= <span class="number">6</span>, max = <span class="number">20</span>, groups = &#123;Save<span class="class">.<span class="keyword">class</span>, <span class="title">Update</span>.<span class="title">class</span>&#125;)</span></span><br><span class="line"><span class="class">    <span class="title">private</span> <span class="title">String</span> <span class="title">password</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 保存的时候校验分组</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">Save</span> </span>&#123;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 更新的时候校验分组</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">Update</span> </span>&#123;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li><strong><code>@Validated</code>注解上指定校验分组</strong></li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@PostMapping</span>(<span class="string">"/save"</span>)</span><br><span class="line"><span class="function"><span class="keyword">public</span> Result <span class="title">saveUser</span><span class="params">(@RequestBody @Validated(UserDTO.Save.class)</span> UserDTO userDTO) </span>&#123;</span><br><span class="line">    <span class="comment">// 校验通过，才会执行业务逻辑处理</span></span><br><span class="line">    <span class="keyword">return</span> Result.ok();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@PostMapping</span>(<span class="string">"/update"</span>)</span><br><span class="line"><span class="function"><span class="keyword">public</span> Result <span class="title">updateUser</span><span class="params">(@RequestBody @Validated(UserDTO.Update.class)</span> UserDTO userDTO) </span>&#123;</span><br><span class="line">    <span class="comment">// 校验通过，才会执行业务逻辑处理</span></span><br><span class="line">    <span class="keyword">return</span> Result.ok();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="嵌套校验"><a href="#嵌套校验" class="headerlink" title="嵌套校验"></a>嵌套校验</h3><p>前面的示例中，<code>DTO</code>类里面的字段都是<code>基本数据类型</code>和<code>String</code>类型。但是实际场景中，有可能某个字段也是一个对象，这种情况先，可以使用<code>嵌套校验</code>。比如，上面保存<code>User</code>信息的时候同时还带有<code>Job</code>信息。需要注意的是，<strong>此时<code>DTO</code>类的对应字段必须标记<code>@Valid</code>注解</strong>。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UserDTO</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Min</span>(value = <span class="number">10000000000000000L</span>, groups = Update<span class="class">.<span class="keyword">class</span>)</span></span><br><span class="line"><span class="class">    <span class="title">private</span> <span class="title">Long</span> <span class="title">userId</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@NotNull</span>(groups = &#123;Save<span class="class">.<span class="keyword">class</span>, <span class="title">Update</span>.<span class="title">class</span>&#125;)</span></span><br><span class="line"><span class="class">    @<span class="title">Length</span>(<span class="title">min</span> </span>= <span class="number">2</span>, max = <span class="number">10</span>, groups = &#123;Save<span class="class">.<span class="keyword">class</span>, <span class="title">Update</span>.<span class="title">class</span>&#125;)</span></span><br><span class="line"><span class="class">    <span class="title">private</span> <span class="title">String</span> <span class="title">userName</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@NotNull</span>(groups = &#123;Save<span class="class">.<span class="keyword">class</span>, <span class="title">Update</span>.<span class="title">class</span>&#125;)</span></span><br><span class="line"><span class="class">    @<span class="title">Length</span>(<span class="title">min</span> </span>= <span class="number">6</span>, max = <span class="number">20</span>, groups = &#123;Save<span class="class">.<span class="keyword">class</span>, <span class="title">Update</span>.<span class="title">class</span>&#125;)</span></span><br><span class="line"><span class="class">    <span class="title">private</span> <span class="title">String</span> <span class="title">account</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@NotNull</span>(groups = &#123;Save<span class="class">.<span class="keyword">class</span>, <span class="title">Update</span>.<span class="title">class</span>&#125;)</span></span><br><span class="line"><span class="class">    @<span class="title">Length</span>(<span class="title">min</span> </span>= <span class="number">6</span>, max = <span class="number">20</span>, groups = &#123;Save<span class="class">.<span class="keyword">class</span>, <span class="title">Update</span>.<span class="title">class</span>&#125;)</span></span><br><span class="line"><span class="class">    <span class="title">private</span> <span class="title">String</span> <span class="title">password</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@NotNull</span>(groups = &#123;Save<span class="class">.<span class="keyword">class</span>, <span class="title">Update</span>.<span class="title">class</span>&#125;)</span></span><br><span class="line"><span class="class">    @<span class="title">Valid</span></span></span><br><span class="line"><span class="class">    <span class="title">private</span> <span class="title">Job</span> <span class="title">job</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Data</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">Job</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="meta">@Min</span>(value = <span class="number">1</span>, groups = Update<span class="class">.<span class="keyword">class</span>)</span></span><br><span class="line"><span class="class">        <span class="title">private</span> <span class="title">Long</span> <span class="title">jobId</span></span>;</span><br><span class="line"></span><br><span class="line">        <span class="meta">@NotNull</span>(groups = &#123;Save<span class="class">.<span class="keyword">class</span>, <span class="title">Update</span>.<span class="title">class</span>&#125;)</span></span><br><span class="line"><span class="class">        @<span class="title">Length</span>(<span class="title">min</span> </span>= <span class="number">2</span>, max = <span class="number">10</span>, groups = &#123;Save<span class="class">.<span class="keyword">class</span>, <span class="title">Update</span>.<span class="title">class</span>&#125;)</span></span><br><span class="line"><span class="class">        <span class="title">private</span> <span class="title">String</span> <span class="title">jobName</span></span>;</span><br><span class="line"></span><br><span class="line">        <span class="meta">@NotNull</span>(groups = &#123;Save<span class="class">.<span class="keyword">class</span>, <span class="title">Update</span>.<span class="title">class</span>&#125;)</span></span><br><span class="line"><span class="class">        @<span class="title">Length</span>(<span class="title">min</span> </span>= <span class="number">2</span>, max = <span class="number">10</span>, groups = &#123;Save<span class="class">.<span class="keyword">class</span>, <span class="title">Update</span>.<span class="title">class</span>&#125;)</span></span><br><span class="line"><span class="class">        <span class="title">private</span> <span class="title">String</span> <span class="title">position</span></span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 保存的时候校验分组</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">Save</span> </span>&#123;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 更新的时候校验分组</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">Update</span> </span>&#123;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>嵌套校验可以结合分组校验一起使用。还有就是<code>嵌套集合校验</code>会对集合里面的每一项都进行校验，例如<code>List&lt;Job&gt;</code>字段会对这个<code>list</code>里面的每一个<code>Job</code>对象都进行校验。</p>
</blockquote>
<h3 id="集合校验"><a href="#集合校验" class="headerlink" title="集合校验"></a>集合校验</h3><p>如果请求体直接传递了<code>json</code>数组给后台，并希望对数组中的每一项都进行参数校验。此时，如果我们直接使用<code>java.util.Collection</code>下的<code>list</code>或者<code>set</code>来接收数据，参数校验并不会生效！我们可以使用自定义<code>list</code>集合来接收参数：</p>
<ul>
<li><strong>包装<code>List</code>类型，并声明<code>@Valid</code>注解</strong></li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ValidationList</span>&lt;<span class="title">E</span>&gt; <span class="keyword">implements</span> <span class="title">List</span>&lt;<span class="title">E</span>&gt; </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Delegate</span> <span class="comment">// @Delegate是lombok注解</span></span><br><span class="line">    <span class="meta">@Valid</span> <span class="comment">// 一定要加@Valid注解</span></span><br><span class="line">    <span class="keyword">public</span> List&lt;E&gt; list = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 一定要记得重写toString方法</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> list.toString();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p><code>@Delegate</code>注解受<code>lombok</code>版本限制，<code>1.18.6</code>以上版本可支持。如果校验不通过，会抛出<code>NotReadablePropertyException</code>，同样可以使用统一异常进行处理。</p>
</blockquote>
<p>比如，我们需要一次性保存多个<code>User</code>对象，<code>Controller</code>层的方法可以这么写：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@PostMapping</span>(<span class="string">"/saveList"</span>)</span><br><span class="line"><span class="function"><span class="keyword">public</span> Result <span class="title">saveList</span><span class="params">(@RequestBody @Validated(UserDTO.Save.class)</span> ValidationList&lt;UserDTO&gt; userList) </span>&#123;</span><br><span class="line">    <span class="comment">// 校验通过，才会执行业务逻辑处理</span></span><br><span class="line">    <span class="keyword">return</span> Result.ok();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="自定义校验"><a href="#自定义校验" class="headerlink" title="自定义校验"></a>自定义校验</h3><p>业务需求总是比框架提供的这些简单校验要复杂的多，我们可以自定义校验来满足我们的需求。自定义<code>spring validation</code>非常简单，假设我们自定义<code>加密id</code>（由数字或者<code>a-f</code>的字母组成，<code>32-256</code>长度）校验，主要分为两步：</p>
<ul>
<li><strong>自定义约束注解</strong></li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Target</span>(&#123;METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER&#125;)</span><br><span class="line"><span class="meta">@Retention</span>(RUNTIME)</span><br><span class="line"><span class="meta">@Documented</span></span><br><span class="line"><span class="meta">@Constraint</span>(validatedBy = &#123;EncryptIdValidator<span class="class">.<span class="keyword">class</span>&#125;)</span></span><br><span class="line"><span class="class"><span class="title">public</span> @<span class="title">interface</span> <span class="title">EncryptId</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 默认错误消息</span></span><br><span class="line">    <span class="function">String <span class="title">message</span><span class="params">()</span> <span class="keyword">default</span> "加密id格式错误"</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 分组</span></span><br><span class="line">    Class&lt;?&gt;[] groups() <span class="keyword">default</span> &#123;&#125;;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 负载</span></span><br><span class="line">    Class&lt;? extends Payload&gt;[] payload() <span class="keyword">default</span> &#123;&#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>实现<code>ConstraintValidator</code>接口编写约束校验器</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">EncryptIdValidator</span> <span class="keyword">implements</span> <span class="title">ConstraintValidator</span>&lt;<span class="title">EncryptId</span>, <span class="title">String</span>&gt; </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Pattern PATTERN = Pattern.compile(<span class="string">"^[a-f\\d]&#123;32,256&#125;$"</span>);</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">isValid</span><span class="params">(String value, ConstraintValidatorContext context)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 不为null才进行校验</span></span><br><span class="line">        <span class="keyword">if</span> (value != <span class="keyword">null</span>) &#123;</span><br><span class="line">            Matcher matcher = PATTERN.matcher(value);</span><br><span class="line">            <span class="keyword">return</span> matcher.find();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这样我们就可以使用<code>@EncryptId</code>进行参数校验了！</p>
<h3 id="编程式校验"><a href="#编程式校验" class="headerlink" title="编程式校验"></a>编程式校验</h3><p>上面的示例都是基于<code>注解</code>来实现自动校验的，在某些情况下，我们可能希望以<code>编程方式</code>调用验证。这个时候可以注入<code>javax.validation.Validator</code>对象，然后再调用其<code>api</code>。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Autowired</span></span><br><span class="line"><span class="keyword">private</span> javax.validation.Validator globalValidator;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 编程式校验</span></span><br><span class="line"><span class="meta">@PostMapping</span>(<span class="string">"/saveWithCodingValidate"</span>)</span><br><span class="line"><span class="function"><span class="keyword">public</span> Result <span class="title">saveWithCodingValidate</span><span class="params">(@RequestBody UserDTO userDTO)</span> </span>&#123;</span><br><span class="line">    Set&lt;ConstraintViolation&lt;UserDTO&gt;&gt; validate = globalValidator.validate(userDTO, UserDTO.Save<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">    <span class="comment">// 如果校验通过，validate为空；否则，validate包含未校验通过项</span></span><br><span class="line">    <span class="keyword">if</span> (validate.isEmpty()) &#123;</span><br><span class="line">        <span class="comment">// 校验通过，才会执行业务逻辑处理</span></span><br><span class="line"></span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">for</span> (ConstraintViolation&lt;UserDTO&gt; userDTOConstraintViolation : validate) &#123;</span><br><span class="line">            <span class="comment">// 校验失败，做其它逻辑</span></span><br><span class="line">            System.out.println(userDTOConstraintViolation);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> Result.ok();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="快速失败-Fail-Fast"><a href="#快速失败-Fail-Fast" class="headerlink" title="快速失败(Fail Fast)"></a>快速失败(Fail Fast)</h3><p><code>Spring Validation</code>默认会校验完所有字段，然后才抛出异常。可以通过一些简单的配置，开启<code>Fali Fast</code>模式，一旦校验失败就立即返回。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Bean</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> Validator <span class="title">validator</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator<span class="class">.<span class="keyword">class</span>)</span></span><br><span class="line"><span class="class">            .<span class="title">configure</span>()</span></span><br><span class="line"><span class="class">            // 快速失败模式</span></span><br><span class="line"><span class="class">            .<span class="title">failFast</span>(<span class="title">true</span>)</span></span><br><span class="line"><span class="class">            .<span class="title">buildValidatorFactory</span>()</span>;</span><br><span class="line">    <span class="keyword">return</span> validatorFactory.getValidator();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="Valid和-Validated区别"><a href="#Valid和-Validated区别" class="headerlink" title="@Valid和@Validated区别"></a><code>@Valid</code>和<code>@Validated</code>区别</h3><table>
<thead>
<tr>
<th>区别</th>
<th>@Valid</th>
<th>@Validated</th>
</tr>
</thead>
<tbody><tr>
<td>提供者</td>
<td>JSR-303规范</td>
<td>Spring</td>
</tr>
<tr>
<td>是否支持分组</td>
<td>不支持</td>
<td>支持</td>
</tr>
<tr>
<td>标注位置</td>
<td>METHOD, FIELD, CONSTRUCTOR, PARAMETER, TYPE_USE</td>
<td>TYPE, METHOD, PARAMETER</td>
</tr>
<tr>
<td>嵌套校验</td>
<td>支持</td>
<td>不支持</td>
</tr>
</tbody></table>
<h2 id="实现原理"><a href="#实现原理" class="headerlink" title="实现原理"></a>实现原理</h2><h3 id="requestBody参数校验实现原理"><a href="#requestBody参数校验实现原理" class="headerlink" title="requestBody参数校验实现原理"></a><code>requestBody</code>参数校验实现原理</h3><p>在<code>spring-mvc</code>中，<code>RequestResponseBodyMethodProcessor</code>是用于解析<code>@RequestBody</code>标注的参数以及处理<code>@ResponseBody</code>标注方法的返回值的。显然，执行参数校验的逻辑肯定就在解析参数的方法<code>resolveArgument()</code>中：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RequestResponseBodyMethodProcessor</span> <span class="keyword">extends</span> <span class="title">AbstractMessageConverterMethodProcessor</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">resolveArgument</span><span class="params">(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,</span></span></span><br><span class="line"><span class="function"><span class="params">                                  NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line"></span><br><span class="line">        parameter = parameter.nestedIfOptional();</span><br><span class="line">        <span class="comment">//将请求数据封装到DTO对象中</span></span><br><span class="line">        Object arg = readWithMessageConverters(webRequest, parameter, parameter.getNestedGenericParameterType());</span><br><span class="line">        String name = Conventions.getVariableNameForParameter(parameter);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (binderFactory != <span class="keyword">null</span>) &#123;</span><br><span class="line">            WebDataBinder binder = binderFactory.createBinder(webRequest, arg, name);</span><br><span class="line">            <span class="keyword">if</span> (arg != <span class="keyword">null</span>) &#123;</span><br><span class="line">                <span class="comment">// 执行数据校验</span></span><br><span class="line">                validateIfApplicable(binder, parameter);</span><br><span class="line">                <span class="keyword">if</span> (binder.getBindingResult().hasErrors() &amp;&amp; isBindExceptionRequired(binder, parameter)) &#123;</span><br><span class="line">                    <span class="keyword">throw</span> <span class="keyword">new</span> MethodArgumentNotValidException(parameter, binder.getBindingResult());</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">if</span> (mavContainer != <span class="keyword">null</span>) &#123;</span><br><span class="line">                mavContainer.addAttribute(BindingResult.MODEL_KEY_PREFIX + name, binder.getBindingResult());</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> adaptArgumentIfNecessary(arg, parameter);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>可以看到，<code>resolveArgument()</code>调用了<code>validateIfApplicable()</code>进行参数校验。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">validateIfApplicable</span><span class="params">(WebDataBinder binder, MethodParameter parameter)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 获取参数注解，比如@RequestBody、@Valid、@Validated</span></span><br><span class="line">    Annotation[] annotations = parameter.getParameterAnnotations();</span><br><span class="line">    <span class="keyword">for</span> (Annotation ann : annotations) &#123;</span><br><span class="line">        <span class="comment">// 先尝试获取@Validated注解</span></span><br><span class="line">        Validated validatedAnn = AnnotationUtils.getAnnotation(ann, Validated<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">        <span class="comment">//如果直接标注了@Validated，那么直接开启校验。</span></span><br><span class="line">        <span class="comment">//如果没有，那么判断参数前是否有Valid起头的注解。</span></span><br><span class="line">        <span class="keyword">if</span> (validatedAnn != <span class="keyword">null</span> || ann.annotationType().getSimpleName().startsWith(<span class="string">"Valid"</span>)) &#123;</span><br><span class="line">            Object hints = (validatedAnn != <span class="keyword">null</span> ? validatedAnn.value() : AnnotationUtils.getValue(ann));</span><br><span class="line">            Object[] validationHints = (hints <span class="keyword">instanceof</span> Object[] ? (Object[]) hints : <span class="keyword">new</span> Object[] &#123;hints&#125;);</span><br><span class="line">            <span class="comment">//执行校验</span></span><br><span class="line">            binder.validate(validationHints);</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>看到这里，大家应该能明白为什么这种场景下<code>@Validated</code>、<code>@Valid</code>两个注解可以混用。我们接下来继续看<code>WebDataBinder.validate()</code>实现。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">validate</span><span class="params">(Object target, Errors errors, Object... validationHints)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.targetValidator != <span class="keyword">null</span>) &#123;</span><br><span class="line">        processConstraintViolations(</span><br><span class="line">            <span class="comment">//此处调用Hibernate Validator执行真正的校验</span></span><br><span class="line">            <span class="keyword">this</span>.targetValidator.validate(target, asValidationGroups(validationHints)), errors);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>最终发现底层最终还是调用了<code>Hibernate Validator</code>进行真正的校验处理。</p>
<h3 id="方法级别的参数校验实现原理"><a href="#方法级别的参数校验实现原理" class="headerlink" title="方法级别的参数校验实现原理"></a>方法级别的参数校验实现原理</h3><p>上面提到的将参数一个个平铺到方法参数中，然后在每个参数前面声明<code>约束注解</code>的校验方式，就是方法级别的参数校验。实际上，这种方式可用于任何<code>Spring Bean</code>的方法上，比如<code>Controller</code>/<code>Service</code>等。<strong>其底层实现原理就是<code>AOP</code>，具体来说是通过<code>MethodValidationPostProcessor</code>动态注册<code>AOP</code>切面，然后使用<code>MethodValidationInterceptor</code>对切点方法织入增强</strong>。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MethodValidationPostProcessor</span> <span class="keyword">extends</span> <span class="title">AbstractBeanFactoryAwareAdvisingPostProcessorimplements</span> <span class="title">InitializingBean</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">afterPropertiesSet</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">//为所有`@Validated`标注的Bean创建切面</span></span><br><span class="line">        Pointcut pointcut = <span class="keyword">new</span> AnnotationMatchingPointcut(<span class="keyword">this</span>.validatedAnnotationType, <span class="keyword">true</span>);</span><br><span class="line">        <span class="comment">//创建Advisor进行增强</span></span><br><span class="line">        <span class="keyword">this</span>.advisor = <span class="keyword">new</span> DefaultPointcutAdvisor(pointcut, createMethodValidationAdvice(<span class="keyword">this</span>.validator));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//创建Advice，本质就是一个方法拦截器</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> Advice <span class="title">createMethodValidationAdvice</span><span class="params">(@Nullable Validator validator)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> (validator != <span class="keyword">null</span> ? <span class="keyword">new</span> MethodValidationInterceptor(validator) : <span class="keyword">new</span> MethodValidationInterceptor());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>接着看一下<code>MethodValidationInterceptor</code>：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MethodValidationInterceptor</span> <span class="keyword">implements</span> <span class="title">MethodInterceptor</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">invoke</span><span class="params">(MethodInvocation invocation)</span> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">        <span class="comment">//无需增强的方法，直接跳过</span></span><br><span class="line">        <span class="keyword">if</span> (isFactoryBeanMetadataMethod(invocation.getMethod())) &#123;</span><br><span class="line">            <span class="keyword">return</span> invocation.proceed();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//获取分组信息</span></span><br><span class="line">        Class&lt;?&gt;[] groups = determineValidationGroups(invocation);</span><br><span class="line">        ExecutableValidator execVal = <span class="keyword">this</span>.validator.forExecutables();</span><br><span class="line">        Method methodToValidate = invocation.getMethod();</span><br><span class="line">        Set&lt;ConstraintViolation&lt;Object&gt;&gt; result;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">//方法入参校验，最终还是委托给Hibernate Validator来校验</span></span><br><span class="line">            result = execVal.validateParameters(</span><br><span class="line">                invocation.getThis(), methodToValidate, invocation.getArguments(), groups);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">catch</span> (IllegalArgumentException ex) &#123;</span><br><span class="line">            ...</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//有异常直接抛出</span></span><br><span class="line">        <span class="keyword">if</span> (!result.isEmpty()) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> ConstraintViolationException(result);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//真正的方法调用</span></span><br><span class="line">        Object returnValue = invocation.proceed();</span><br><span class="line">        <span class="comment">//对返回值做校验，最终还是委托给Hibernate Validator来校验</span></span><br><span class="line">        result = execVal.validateReturnValue(invocation.getThis(), methodToValidate, returnValue, groups);</span><br><span class="line">        <span class="comment">//有异常直接抛出</span></span><br><span class="line">        <span class="keyword">if</span> (!result.isEmpty()) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> ConstraintViolationException(result);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> returnValue;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>实际上，不管是<code>requestBody参数校验</code>还是<code>方法级别的校验</code>，最终都是调用<code>Hibernate Validator</code>执行校验，<code>Spring Validation</code>只是做了一层封装</strong>。</p>
<blockquote>
<p>原创不易，觉得文章写得不错的小伙伴，点个赞👍 鼓励一下吧~</p>
</blockquote>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/spring/" rel="tag"># spring</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/posts/293834368/" rel="prev" title="面试中的老大难-mysql事务和锁，一次性讲清楚！">
      <i class="fa fa-chevron-left"></i> 面试中的老大难-mysql事务和锁，一次性讲清楚！
    </a></div>
      <div class="post-nav-item">
    <a href="/posts/1294535823/" rel="next" title="必须了解的mysql三大日志-binlog、redo log和undo log">
      必须了解的mysql三大日志-binlog、redo log和undo log <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#简单使用"><span class="nav-number">1.</span> <span class="nav-text">简单使用</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#引入依赖"><span class="nav-number">1.1.</span> <span class="nav-text">引入依赖</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#requestBody参数校验"><span class="nav-number">1.2.</span> <span class="nav-text">requestBody参数校验</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#requestParam-PathVariable参数校验"><span class="nav-number">1.3.</span> <span class="nav-text">requestParam&#x2F;PathVariable参数校验</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#统一异常处理"><span class="nav-number">1.4.</span> <span class="nav-text">统一异常处理</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#进阶使用"><span class="nav-number">2.</span> <span class="nav-text">进阶使用</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#分组校验"><span class="nav-number">2.1.</span> <span class="nav-text">分组校验</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#嵌套校验"><span class="nav-number">2.2.</span> <span class="nav-text">嵌套校验</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#集合校验"><span class="nav-number">2.3.</span> <span class="nav-text">集合校验</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#自定义校验"><span class="nav-number">2.4.</span> <span class="nav-text">自定义校验</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#编程式校验"><span class="nav-number">2.5.</span> <span class="nav-text">编程式校验</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#快速失败-Fail-Fast"><span class="nav-number">2.6.</span> <span class="nav-text">快速失败(Fail Fast)</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Valid和-Validated区别"><span class="nav-number">2.7.</span> <span class="nav-text">@Valid和@Validated区别</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#实现原理"><span class="nav-number">3.</span> <span class="nav-text">实现原理</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#requestBody参数校验实现原理"><span class="nav-number">3.1.</span> <span class="nav-text">requestBody参数校验实现原理</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#方法级别的参数校验实现原理"><span class="nav-number">3.2.</span> <span class="nav-text">方法级别的参数校验实现原理</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="陈添明"
      src="/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">陈添明</p>
  <div class="site-description" itemprop="description">一个爱看国漫的程序猿</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">17</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">3</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">6</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">陈添明</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-area"></i>
    </span>
    <span title="站点总字数">156k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">6:30</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script size="300" alpha="0.6" zIndex="-1" src="//cdn.jsdelivr.net/gh/theme-next/theme-next-canvas-ribbon@1/canvas-ribbon.js"></script>
  <script src="/lib/anime.min.js"></script>
  <script src="//cdn.jsdelivr.net/gh/theme-next/theme-next-pjax@0/pjax.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/lozad@1/dist/lozad.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>

  <script>
var pjax = new Pjax({
  selectors: [
    'head title',
    '#page-configurations',
    '.content-wrap',
    '.post-toc-wrap',
    '.languages',
    '#pjax'
  ],
  switches: {
    '.post-toc-wrap': Pjax.switches.innerHTML
  },
  analytics: false,
  cacheBust: false,
  scrollTo : !CONFIG.bookmark.enable
});

window.addEventListener('pjax:success', () => {
  document.querySelectorAll('script[data-pjax], script#page-configurations, #pjax script').forEach(element => {
    var code = element.text || element.textContent || element.innerHTML || '';
    var parent = element.parentNode;
    parent.removeChild(element);
    var script = document.createElement('script');
    if (element.id) {
      script.id = element.id;
    }
    if (element.className) {
      script.className = element.className;
    }
    if (element.type) {
      script.type = element.type;
    }
    if (element.src) {
      script.src = element.src;
      // Force synchronous loading of peripheral JS.
      script.async = false;
    }
    if (element.dataset.pjax !== undefined) {
      script.dataset.pjax = '';
    }
    if (code !== '') {
      script.appendChild(document.createTextNode(code));
    }
    parent.appendChild(script);
  });
  NexT.boot.refresh();
  // Define Motion Sequence & Bootstrap Motion.
  if (CONFIG.motion.enable) {
    NexT.motion.integrator
      .init()
      .add(NexT.motion.middleWares.subMenu)
      .add(NexT.motion.middleWares.postList)
      .bootstrap();
  }
  NexT.utils.updateSidebarPosition();
});
</script>




  




  
<script src="/js/local-search.js"></script>













    <div id="pjax">
  

  
  <script src="//cdn.jsdelivr.net/npm/quicklink@1/dist/quicklink.umd.js"></script>
  <script>
      window.addEventListener('load', () => {
      quicklink({
        timeout : 3000,
        priority: true,
        ignores : [uri => uri.includes('#'),uri => uri === 'https://chentianming11.github.io/posts/3181057117/',]
      });
      });
  </script>


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//unpkg.com/valine/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : true,
      appId      : 'SoPxUkme2aynTULaNuIc5TIq-gzGzoHsz',
      appKey     : '4TDP7SMCbgDKTOGGUtpIeA0H',
      placeholder: "留下点足迹吧~",
      avatar     : 'mm',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : false,
      lang       : '' || 'zh-cn',
      path       : location.pathname,
      recordIP   : false,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>

    </div>
</body>
</html>
